import re
from pathlib import Path

class Module:
    def __init__(self, name, content, file):
        self.name = name
        self.content = content
        self.file = file

    def __repr__(self):
        return self.name

def process_comment(text):
    """去除多行和单行注释"""
    text = re.sub(r"/\*.*?\*/", "", text, flags=re.DOTALL)
    text = re.sub(r"//.*?\n", "\n", text)
    return text

def find_modules(file_path: Path):
    """从文件中查找模块"""
    with open(file_path, "r") as f:
        content = process_comment(f.read())
    
    matches = re.findall(r"(module\s+(\w+).*?endmodule)", content, re.DOTALL)
    modules = [Module(match[1], match[0], file_path) for match in matches]
    return modules

def find_other_mods(mod: Module, mods):
    """查找其他模块在当前模块中的引用"""
    return [m for m in mods if re.search(rf"\b{m.name}\b", mod.content) and m.name != mod.name]

def is_top(mod_name, mod_dict):
    """检查给定模块是否为顶层模块"""
    for mod_list in mod_dict.values():
        if mod_name in mod_list:
            return False
    return True

def get_top_modules(src_path: str):
    """获取指定目录下的顶层模块"""
    all_mods = []
    for f in Path(src_path).glob("**/*.v"):
        modules = find_modules(f)
        all_mods.extend(modules)

    top_list = []
    all_list = {}
    for mod in all_mods:
        temp = find_other_mods(mod, all_mods)
        all_list[mod.name] = [m.name for m in temp]

    for k in all_list.keys():
        find_dict = all_list.copy()
        del find_dict[k]
        ret = is_top(k, find_dict)

        for mod in all_list[k]:
            # 使用正确的对象来检查内容
            for m in all_mods:
                if m.name == mod:
                    if re.search(rf"\b{k}\b", m.content) and k != m.name:
                        ret = False
                    break
        if ret:
            top_list.append(k)

    return top_list

